package boot.spring.service;

import boot.spring.po.MongoGeoUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
public class TestService {


    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新或插入对象
     */
    public void createMongoGeoUsers() {//批量添加,600w条数据比redis添加慢了很多很多，要等一小会的，建议泡杯茶，回头复习一下之前的文章
        for (int i = 0; i < 6000000; i++) {
            BigDecimal lng = new BigDecimal(Math.random() * (130 - 100) + 100).setScale(10, BigDecimal.ROUND_HALF_UP);
            BigDecimal lat = new BigDecimal(Math.random() * 20 + 20).setScale(10, BigDecimal.ROUND_HALF_UP);

            MongoGeoUser mongoGeoUser = new MongoGeoUser(new Long(i), "user1", new GeoJsonPoint(lng.doubleValue(), lat.doubleValue()), new Date());
            mongoTemplate.save(mongoGeoUser);
        }
    }

    public void nearSphere() {
        Query query = new Query(Criteria.where("location")
                .nearSphere(new GeoJsonPoint(120.666666666, 30.888888888))
                .maxDistance(5000).minDistance(1000));
        List<MongoGeoUser> venues = mongoTemplate.find(query, MongoGeoUser.class);

        for (MongoGeoUser venue : venues) {
            System.out.println(venue);
        }
    }

    public void nearQuery() {
        long startTime = System.currentTimeMillis();
        NearQuery near = NearQuery
                .near(new GeoJsonPoint(120.666666666, 30.888888888))
                .spherical(true)
                .maxDistance(5, Metrics.KILOMETERS)
                .minDistance(1, Metrics.KILOMETERS)
                .num(10);
        GeoResults<MongoGeoUser> results = mongoTemplate.geoNear(near, MongoGeoUser.class);

        long endTime = System.currentTimeMillis();
        System.out.println("程序运行时间：" + (endTime - startTime) + "ms");

        for (GeoResult<MongoGeoUser> result : results) {
            System.out.println(result);
        }
    }


}
